package javabase.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Set;

public class NioClientTest {

    public static void main(String[] args) throws IOException {
        try (SocketChannel channel = SocketChannel.open()) {

            // 设置非阻塞模式
            channel.configureBlocking(false);

            channel.connect(new InetSocketAddress(1000));


            Selector selector = Selector.open();

            channel.register(selector, SelectionKey.OP_CONNECT);

            int key = selector.select(10000);

            SelectionKey sKey = null;
            if (key > 0) {
                Set<SelectionKey> keys = selector.selectedKeys();
                for (SelectionKey key1 : keys) {
                    // 连接事件
                    if (key1.isConnectable()) {
                        SocketChannel channel1 = (SocketChannel) key1.channel();
                        channel1.configureBlocking(false);


                        sKey = channel1.register(selector, SelectionKey.OP_READ);

                        channel1.finishConnect();
                    } else if (key1.isReadable()) {
                        ByteBuffer buffer = ByteBuffer.allocate(1024);

                        SocketChannel channel1 = (SocketChannel) key1.channel();

                        int readBytes = 0;
                        try {
                            int ret = 0;
                            try {
                                while ((ret = channel1.read(buffer)) > 0 ) {
                                    readBytes += ret;
                                }
                            } finally {
                                buffer.flip();
                            }
                        } finally {
                            if (buffer != null) {
                                buffer.clear();
                            }
                        }
                    } else if (key1.isWritable()) {
                        key1.interestOps(key1.interestOps() & (~SelectionKey.OP_WRITE));

                        SocketChannel channel1 = (SocketChannel) key1.channel();

                        int writtenSize = channel1.write(ByteBuffer.allocate(1024));

                        if (writtenSize == 0) {
                            key1.interestOps(key1.interestOps() | SelectionKey.OP_WRITE);
                        }
                    }
                }
                selector.selectedKeys().clear();
            }
            int wSize = channel.write(ByteBuffer.allocate(1024));
            if (wSize == 0) {

            }

        }



    }

}
